package fhq.hcmute.modernshopping.camera;

import java.io.IOException;

import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * @author: Hien Nguyen Le
 * @emai: hien.nguyenle.it@gmail.com
 * 
 */
public class CameraPreview extends SurfaceView implements
		SurfaceHolder.Callback {
	private static final String TAG = "nglehien";
	public static final int DISPLAY_ORIENTATION = 90;
	private Camera camera;
	private SurfaceHolder surfaceHolder;
	private Camera.PreviewCallback previewCallback;
	private Camera.AutoFocusCallback autoFocusCallback;

	public CameraPreview(Context context, Camera camera,
			Camera.PreviewCallback previewCallback,
			Camera.AutoFocusCallback autoFocusCb) {
		super(context);
		this.camera = camera;

		this.surfaceHolder = getHolder();
		this.surfaceHolder.addCallback(this);
		this.previewCallback = previewCallback;
		this.autoFocusCallback = autoFocusCb;
	}

	public CameraPreview(Context context, Camera camera,
			Camera.PreviewCallback previewCallback,
			Camera.AutoFocusCallback autoFocusCb, SurfaceHolder surfaceHolder) {
		super(context);
		this.camera = camera;

		this.surfaceHolder = surfaceHolder;
		this.surfaceHolder.addCallback(this);
		this.previewCallback = previewCallback;
		this.autoFocusCallback = autoFocusCb;
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		try {
			this.camera.setPreviewDisplay(holder);
		} catch (IOException ioe) {
			Log.d(TAG, "surfaceCreated error:" + ioe.getMessage());
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		if (holder == null) {
			return;
		}
		try {
			camera.stopPreview();
		} catch (Exception e) {
			Log.d(TAG, "surfaceChanged error:" + e.getMessage());
		}

		try {
			this.camera.setDisplayOrientation(DISPLAY_ORIENTATION);
			this.camera.setPreviewDisplay(holder);
			this.camera.setPreviewCallback(this.previewCallback);
			this.camera.autoFocus(this.autoFocusCallback);
			this.camera.startPreview();
		} catch (Exception e) {
			Log.d(TAG, "surfaceChanged error:" + e.getMessage());
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {

	}
}
